<template>
  <div class="home">
    <!-- 商品分类 -->
    <section class="category-section">
      <h3>商品分类</h3>
      <el-radio-group v-model="selectedCategory" size="large" class="category-radio-list">
        <el-radio :label="''">全部</el-radio>
        <el-radio
          v-for="category in categories"
          :key="category.id"
          :label="category.id"
        >
          {{ category.title }}
        </el-radio>
      </el-radio-group>
    </section>

    <!-- 推荐商品 -->
    <section class="products-section">
      <h2>推荐商品</h2>
      <div class="product-grid">
        <div
            v-for="item in products"
            :key="item.id"
            class="product-card"
            @click="goToDetail(item)"
            style="cursor:pointer"
        >
          <img :src="item.mainImage ? item.mainImage : '/public/assets/img/book.jpg'" />
          <p class="product-title">{{ item.name || item.title }}</p>
          <p class="product-price">¥{{ item.price }}</p>
          <button class="buy-btn" @click.stop="handleAddToCart(item)">添加进购物车</button>
        </div>
      </div>
    </section>
  </div>
</template>


<script setup>
import { ref, computed, onMounted } from 'vue'
import { getCategoryTree } from '../api/category'
import { getProductList } from '../api/product'
import { addToCart } from '../api/cart'
import { ElMessage, ElRadioGroup, ElRadio } from 'element-plus'

import { useRouter } from 'vue-router'
const router = useRouter()
// 跳转到商品详情
function goToDetail(item) {
  router.push({ name: 'product-detail', params: { id: item.id } })
}

// 添加进购物车
function handleAddToCart(item) {
  addToCart({ productId: item.id, quantity: 1 }).then(res => {
    if (res.code === 0) {
      ElMessage.success('已添加进购物车')
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  })
}

// 分类数据（动态获取）
const categories = ref([])
// 商品数据（动态获取）
const products = ref([])
// 当前选中的分类id
const selectedCategory = ref('')

// 获取商品列表（全部或按分类）
const fetchProducts = async (categoryId = '') => {
  let res
  if (!categoryId) {
    res = await getProductList({ pageNum: 1, pageSize: 50 })
  } else {
    // 按分类请求
    res = await getProductList({ pageNum: 1, pageSize: 50, categoryId })
  }
  if (res && res.code === 0) {
    products.value = (res.data?.list || []).map(item => ({
      ...item,
      img: item.mainImage || 'book.png'
    }))
  }
}

// 监听分类变化，每次切换都请求API
import { watch } from 'vue'
watch(selectedCategory, (val) => {
  fetchProducts(val)
})

// 获取分类树并适配前端结构
const fetchCategories = async () => {
  const res = await getCategoryTree()
  if (res.code === 0) {
    categories.value = (res.data || []).map(cat => ({
      id: cat.id,
      title: cat.name
    }))
  }
}

// 页面初始加载
onMounted(() => {
  fetchCategories()
  fetchProducts()
})
</script>

<style scoped>
.home {
  background: #f8faff;
  min-height: 100vh;
}

/* 分类样式 */
.category-section {
  max-width: 1200px;
  margin: 50px auto;
}

.category-section h3 {
  margin-bottom: 20px;
  font-size: 24px;
  text-align: center;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 20px;
  justify-items: center;
}

.category-item-wrapper {
  position: relative;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.category-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.category-icon {
  width: 48px;
  height: 48px;
}

.category-item span {
  margin-top: 8px;
  font-weight: 500;
  font-size: 14px;
}

/* 子分类菜单 */
.subcategory-dropdown {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 8px 0;
  list-style: none;
  z-index: 1000;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  min-width: 140px;
}

.subcategory-dropdown li {
  padding: 6px 16px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.subcategory-dropdown li:hover {
  background-color: #f5f7fa;
}

/* 推荐商品 */
.products-section {
  max-width: 1200px;
  margin: 50px auto;
}

.products-section h2 {
  text-align: center;
  margin-bottom: 24px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 30px;
}

.product-card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  padding: 16px;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s, box-shadow 0.2s;
}

.product-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.product-card img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 6px;
}

.product-title {
  margin: 12px 0 6px;
  font-size: 14px;
  color: #333;
}

.product-price {
  color: #f40;
  font-weight: bold;
  margin-bottom: 10px;
}

.buy-btn {
  background: #3182ce;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
}

.buy-btn:hover {
  background: #246bb2;
}
</style>
